package com.myTimeUtils.android.TimeTracker.Schedule;
import com.myTimeUtils.android.TimeTracker.Global.Iterator;
import com.myTimeUtils.android.TimeTracker.Global.Observer;
import com.myTimeUtils.android.TimeTracker.System.CurrentTime;
import android.util.Log;
/**
 * Manages a schedule and allows for iteration through the set schedule.
 *
 * @author Joseph Walker
 */
public class ScheduleManager implements Observer{
	private boolean active;
	private Iterator<Period> iterator;
	private Period currentPeriod;
	private Schedule schedule;
	/**
	 * Constructs a schedule manager.
	 */
	public ScheduleManager(){
		this.init();
	}
	/**
	 * Adds a period to the schedule. 
	 *
	 * @param period	The period to add
	 * @param day		The day to add the period to
	 * @return		True if the period can be added to the scheule
	 */
	public boolean addPeriod(Period period, int day){
		boolean out = this.schedule.addPeriod(period, day);
		this.start();
		return out;
	}
	private void advanceSchedule(){
		Time now = CurrentTime.getTime();
		Time end = null;
		while(this.iterator.hasNext() && !this.iterator.current().beforePeriod(now) && !this.iterator.current().isInPeriod(now)){
			this.iterator.next();
		}
		if(this.iterator.current().isInPeriod(now)){
			this.currentPeriod = this.iterator.current();
		}
		else{
			end = this.iterator.current().getStart();
			this.currentPeriod = new Period(end, "Nothing Scheduled", now);
		}
		Log.d("Process", "Found the proper period");
	}
	/**
	 * Returns the current period.
	 *
	 * @return			The current period.
	 */
	protected Period getCurrentPeriod(){ return this.currentPeriod; }
	private void init(){ 
		this.schedule = new Schedule();	
		this.active = false;
	}
	/**
	 * Updates the schedule to the current period.
	 */
	public void notifyObserver(){
		Log.d("Process", "Update Schedule");
		Log.d("Process", currentPeriod + " ");
		if(this.active && !this.currentPeriod.isInPeriod(CurrentTime.getTime())) this.advanceSchedule();		
	}
	/**
	 * Removes a period to the schedule. 
	 *
	 * @param period	The period to remove
	 * @param day		The day to remove the period from
	 * @return		True if the period can be removed to the scheule
	 */
	public boolean removePeriod(Period period, int day){
		return this.schedule.removePeriod(period, day);
	}
	/**
	 * Starts the iterator. 
	 */
	public void start(){
		this.iterator = schedule.getIterator();
		this.advanceSchedule();
		this.active = true;
	}	
}
